<template>
    <a-menu theme="dark" mode="inline" v-model:openKeys="mainStore().selectedKeys" @openChange="openChange"
        @click="menuCallFun" class="menuTree innerbox-scroll" :style="{
                height: mainStore().containerHeight - mainStore().avatarHeight + 'px'
            }">
        <sub-menu-tree v-for="item in menuTrees" :key="getJsonKey(item)" :value="item" />
    </a-menu>
</template>

<script setup lang='ts'>
import i18n from '@/i18n';
import type { MenuResultDto } from '@/models/menu';
import type { MenuTab } from '@/models/menu-tab';
import { mainStore, setCurrentTab, setMenuTabs } from '@/store/main';
import { toCamelCase } from '@/utils';
import { defineAsyncComponent, markRaw } from 'vue';
import SubMenuTree from './sub-menu-tree.vue';

defineProps<{ menuTrees: Array<MenuResultDto> }>();

/**
 * 手风琴模式
 */
function openChange(openKeys: Array<string>): void {
    const length: number = openKeys.length;
    if (length < 2) {
        return;
    }
    const key: string = openKeys[length - 1];
    if (!JSON.parse(key).parentCode) {
        for (let i: number = 0; i < openKeys.length - 1; ++i) {
            const item: string = openKeys[i];
            if (item !== key && !JSON.parse(item).parentCode) {
                openKeys.splice(i, 1);
                --i;
            }
        }
    }
}

/**
 * 为切换table事件做准备
 * @param item 
 */
function getJsonKey(item: MenuResultDto): string {
    const json: string = JSON.stringify({
        id: item.id,
        icon: item.icon,
        code: item.code,
        parentCode: item.parentCode,
        displayName: item.displayName,
        baseMenuButton: item.baseMenuButton
    });
    return json;
}

/**
 * 切换tab事件
 * @param item 
 */
function menuCallFun(item: any): void {
    const value: MenuResultDto = JSON.parse(item.key);
    const menuTabs: Array<MenuTab> = mainStore().menuTabs;
    for (let i: number = 0; i < menuTabs.length; i++) {
        const item: MenuTab = menuTabs[i];
        if (item.key === value.code) {
            setCurrentTab(item);
            return;
        }
    }
    const code: string = toCamelCase(value.code);
    const displayName: string = 'menuTree.' + code;
    const component = markRaw(
        defineAsyncComponent(() =>
            import(`@/views/upper-computer/${code}/index.vue`)
        )
    );
    const tab: MenuTab = {
        title: value.code ? i18n.global.t(displayName) : value.displayName,
        key: value.code,
        closable: true,
        component: component,
        baseMenuButton: value.baseMenuButton
    };
    menuTabs.push(tab);
    setCurrentTab(tab);
    setMenuTabs(menuTabs);
}
</script>

<style lang="less" scoped>
.menuTree {
    overflow: auto;
}
</style>